package auth

import (
	"strings"

	"gitee.com/zatto/mcenter/apps/endpoint"
	"gitee.com/zatto/mcenter/apps/token"
	"gitee.com/zatto/mcenter/client/rpc"
	client "gitee.com/zatto/mcenter/client/rpc"
	"gitee.com/zatto/mcenter/common/logger"
	"github.com/emicklei/go-restful/v3"
	"github.com/infraboard/mcube/exception"
	"github.com/infraboard/mcube/http/response"
)

type httpAuther struct {
	client *client.ClientSet
}

func NewHttpAuther(client *rpc.ClientSet) *httpAuther {
	return &httpAuther{
		client: client,
	}
}

func (a *httpAuther) AuthFunc(
	req *restful.Request,
	resp *restful.Response,
	next *restful.FilterChain) {
	logger.L().Info().Msgf("%s", req)

	accessRoute := req.SelectedRoute()
	ep := &endpoint.Endpoint{
		Spec: &endpoint.CreateEndpointRequest{
			ServiceId: "",
			Method:    accessRoute.Method(),
			Path:      accessRoute.Path(),
			Operation: accessRoute.Operation(),
		},
	}

	isAuth := accessRoute.Metadata()["auth"]
	if isAuth != nil {
		ep.Spec.Auth = isAuth.(bool)
	}

	if ep.Spec.Auth {
		// 从Header参数中获取token
		authHeader := req.HeaderParameter(token.TOKEN_HEADER_KRY)
		tkList := strings.Split(authHeader, " ")
		if len(tkList) != 2 {
			logger.L().Debug().Msgf("令牌不合法, 格式: Authorization: breaer xxxx")
			response.Failed(resp, exception.NewUnauthorized("无效的令牌"))
			return
		}

		tk := tkList[1]
		logger.L().Debug().Msgf("get token: %s", tk)

		// 校验token
		tkObj, err := a.client.Token().ValidateToken(req.Request.Context(), token.NewValidateTokenRequest(tk))
		if err != nil {
			logger.L().Debug().Msgf("令牌校验失败: %s", err)
			response.Failed(resp, exception.NewUnauthorized("无效的令牌"))
			return
		}

		// 放入上下文
		req.SetAttribute(token.ATTRIBUTE_TOKEN_KEY, tkObj)
	}
	// 继续处理请求
	next.ProcessFilter(req, resp)
}
